import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Menu,
  InputNumber,
  Modal,
  Badge,
  Divider,
  Radio,
  Checkbox
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {nameMaxLength,remarkMaxLength} from '@/utils/rule'
import styles from '../search.less';
const { TextArea } = Input;
const FormItem = Form.Item;
const InputGroup = Input.Group;
const CheckboxGroup = Checkbox.Group;

const CreateForm = Form.create()(props => {
  const { modalVisible, form, updateFn, handleModalVisible, text, serverList } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text) {
        updateFn(fieldsValue,text)
      }
    });
  };  

  return (
    <Modal
      destroyOnClose
      width={640}
      title="编辑管控策略"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="策略名称">
        {form.getFieldDecorator('name', {
          rules: [{required: true,message:'策略名称不能为空'},{max:nameMaxLength()[0],message:nameMaxLength()[1]}],initialValue: text&&text.name || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="风险等级">
        {form.getFieldDecorator('danger', {
          rules: [{required: true,message:'请选择风险等级'}],initialValue: text&&text.sensitiveLevel || ''
        })(<Select disabled placeholder="请选择" style={{width: '100%'}}>
          <Option value="1">1</Option>
          <Option value="2">2</Option>
          <Option value="3">3</Option>
          <Option value="4">4</Option>
          <Option value="5">5</Option>
          <Option value="6">6</Option>
          <Option value="7">7</Option>
          <Option value="8">8</Option>
          <Option value="9">9</Option>
          <Option value="10">10</Option>
        </Select>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="业务处理">
      {form.getFieldDecorator('businessIds', {
          rules: [{required: true,message:'请选择业务处理'}],initialValue: text&&text.businessIds&&text.businessIds.split(",")||[]
        })(
        <CheckboxGroup>
          {
          serverList&&serverList.length?serverList.map((v)=>{
            return <Checkbox key={v.id} value={v.dataDictValue}>{v.dataDictName}</Checkbox>
          }):null
          }          
        </CheckboxGroup>
        )}    
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="备注">
        {form.getFieldDecorator('note',{rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],initialValue: text&&text.remark || ''})(<TextArea
          style={{minHeight: 32}}
          rows={2}
        />)}
      </FormItem>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({ defaultSet, loading }) => ({
  defaultSet,
  loading: loading.models.defaultSet,
}))


@Form.create()
class defaultSet extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    serverList: [],
  };

  columns = [
    {
      title: '策略名称',
      dataIndex: 'name',
    },
    {
      title: '风险等级',
      dataIndex: 'sensitiveLevel',

    },
    {
      title: '业务处理',
      render: (text, record) => {
        const ids = record.businessIds&&record.businessIds.split(",");
        const serverList = this.state.serverList;
        let result = [];
        ids&&ids.length?ids.map((vo) => {
          serverList&&serverList.length?serverList.map((vt) => {
            if(vt.dataDictValue == vo) {
              result.push(vt.dataDictName);
            }
          }):null;
        }):null;
        return result.join(",");
      },    
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: '30%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
        </Fragment>
      ),
    },
  ];

    // 分页查询列表
  pageList(dataDict,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      pageSize: pageSize, 
      pageNum: pageNum, 
    };
    dispatch({
      type: 'defaultSet/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
    this.serverType();
  }

  serverType() {    
    const {dispatch} = this.props;
    dispatch({
      type: 'defaultSet/serverType',
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            serverList: res.data.dataList,
          })
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询  
      this.pageList(fieldsValue);
    });
  };

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const params = {
      id: text.id,
      name: fields.name,
      sensitiveLevel: fields.danger,
      businessIds: fields.businessIds.join(","),
      remark: fields.note,
    }
    dispatch({
      type: 'defaultSet/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }   
      },
    });
    this.handleModalVisible();
  };

  render() {
    const {
      defaultSet: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, stepFormValues, text, serverList } = this.state;
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      updateFn: this.updateFn
    };

    return (
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text} serverList={serverList} />
        <div className={styles.tableList}>
          <TableList
            className={styles.tdPadding}
            hideRowSelection={true}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
      </Card>
    );
  }
}

export default defaultSet;
